//
//  CameraController.m
//  FaceDetector
//
//  Created by Mac on 2016/12/20.
//  Copyright © 2016年 Mac. All rights reserved.
//

#import "CameraController.h"

@interface CameraController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@end

@implementation CameraController

- (UIImagePickerController *)imagePicker {
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
    }
    return _imagePicker;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.imagePicker.delegate = self;
    
}

#pragma mark - 拍照
- (IBAction)openCarema:(id)sender {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"需要真机运行，才能打开相机哦" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    _imagePicker.allowsEditing = false;
    _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:_imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *images = info[UIImagePickerControllerOriginalImage];
    NSData *data = UIImageJPEGRepresentation(images, 0.2);
        NSLog(@"%.2lfM",data.length/1000/1000.0);
    UIImage *image = [UIImage imageWithData:data];
    
    UIImage *image1 = [self imageByScalingAndCroppingForSize:CGSizeMake(image.size.width*0.3,image.size.height*0.3) image:image];
    NSData *data1 = UIImageJPEGRepresentation(image1, 0.2);
    NSLog(@"%.2lfM",data1.length/1000/1000.0);
    UIImage *image2 = [UIImage imageWithData:data1];


//    UIImage *image = [UIImage imageWithCGImage:images.CGImage scale:1 orientation:UIImageOrientationLeftMirrored];

    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    _imageView.image = image2;
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [self facedetect];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)facedetect {
    for (UIView *view in _imageView.subviews) {
        [view removeFromSuperview];
    }
    

    
    NSDictionary *imageOptions =  [NSDictionary dictionaryWithObject:@(5) forKey:CIDetectorImageOrientation];
    CIImage *personciImage = [CIImage imageWithCGImage:_imageView.image.CGImage];
    NSDictionary *opts = [NSDictionary dictionaryWithObject:
                          CIDetectorAccuracyHigh forKey:CIDetectorAccuracy];
    CIDetector *faceDetector=[CIDetector detectorOfType:CIDetectorTypeFace context:nil options:opts];
    NSArray *features = [faceDetector featuresInImage:personciImage options:imageOptions];
    
    
    // 取出所有人脸
    for (CIFaceFeature *faceFeature in features){
        //描绘人脸区域
        UIView* faceView = [[UIView alloc] initWithFrame:[self getCGRect:faceFeature.bounds CIImage:personciImage]];
        faceView.layer.borderWidth = 2;
        faceView.layer.borderColor = [[UIColor redColor] CGColor];
        [_imageView addSubview:faceView];
    
        // 判断是否有左眼位置
        if(faceFeature.hasLeftEyePosition){
            UIView * leftEyeView = [[UIView alloc] initWithFrame:[self getCGRect:CGRectMake(faceFeature.leftEyePosition.x-2.5, faceFeature.leftEyePosition.y-2.5, 5, 5) CIImage:personciImage]];
            leftEyeView.layer.borderWidth = 1;
            leftEyeView.layer.borderColor = [UIColor redColor].CGColor;
            [_imageView addSubview:leftEyeView];
            

        }
        // 判断是否有右眼位置
        if(faceFeature.hasRightEyePosition){
            UIView * rightEyeView = [[UIView alloc] initWithFrame:[self getCGRect:CGRectMake(faceFeature.rightEyePosition.x-2.5, faceFeature.rightEyePosition.y-2.5, 5, 5) CIImage:personciImage]];
            rightEyeView.layer.borderWidth = 1;
            rightEyeView.layer.borderColor = [UIColor redColor].CGColor;
            [_imageView addSubview:rightEyeView];
            
  
        }
        // 判断是否有嘴位置
        if(faceFeature.hasMouthPosition){
            UIView * mouthView = [[UIView alloc] initWithFrame:[self getCGRect:CGRectMake(faceFeature.mouthPosition.x-2.5, faceFeature.mouthPosition.y-2.5, 5, 5) CIImage:personciImage]];
            mouthView.layer.borderWidth = 1;
            mouthView.layer.borderColor = [UIColor redColor].CGColor;
            [_imageView addSubview:mouthView];
            

        }
    }
    if (features.count > 0) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"检测到了人脸" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        
    } else {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"未检测到人脸" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
}
-(CGRect)getCGRect:(CGRect)rect CIImage:(CIImage *)faceImage{

    // 得到图片的尺寸
    CGSize inputImageSize = [faceImage extent].size;
    //将image沿y轴对称
    CGAffineTransform transform = CGAffineTransformScale(CGAffineTransformIdentity, 1, -1);
    //将图片上移
    transform = CGAffineTransformTranslate(transform, 0, -inputImageSize.height);
    
    CGRect faceViewBounds = CGRectApplyAffineTransform(rect, transform);
    CGSize viewSize = _imageView.bounds.size;
    CGFloat scale = MIN(viewSize.width / inputImageSize.width,
                        viewSize.height / inputImageSize.height);
    CGFloat offsetX = (viewSize.width - inputImageSize.width * scale) / 2;
    CGFloat offsetY = (viewSize.height - inputImageSize.height * scale) / 2;
    // 缩放
    CGAffineTransform scaleTransform = CGAffineTransformMakeScale(scale, scale);
    // 修正
    faceViewBounds = CGRectApplyAffineTransform(faceViewBounds,scaleTransform);
    faceViewBounds.origin.x += offsetX;
    faceViewBounds.origin.y += offsetY;
    return faceViewBounds;
}

//图片压缩到指定大小
- (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize image:(UIImage *)image
{
    UIImage *sourceImage = image;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
//    UIGraphicsBeginImageContext(targetSize); // this will crop
    UIGraphicsBeginImageContextWithOptions(targetSize, NO, [UIScreen mainScreen].scale);//图片不失真
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}
@end
